<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="filters">
        <el-form-item>
          <el-input v-model="filters.keywords" placeholder="关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="search">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="departments" highlight-current-row v-loading="listLoading" @selection-change="selsChange"
              style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="sn" label="部门编码" width="120" sortable>
      </el-table-column>
      <el-table-column prop="name" label="名称" width="180" sortable>
      </el-table-column>
      <el-table-column prop="state" label="状态" width="100" sortable>
        <template scope="scope">
          <span style="color:#6cf805;" v-if="scope.row.state === 0">启用</span>
          <span style="color:#bd0707" v-else-if="scope.row.state === -1">禁用</span>
          <span style="color:#292424" v-else>未知</span>
        </template>
      </el-table-column>
      <el-table-column prop="manager.username" label="管理员" width="180" sortable>
      </el-table-column>
      <el-table-column prop="parent.name" label="上级部门" width="180" sortable>
      </el-table-column>
      <el-table-column label="操作">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <!-- 为批量删除按钮绑定事件，当sels的长度大于零时，触发事件 -->
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="pageSize" :total="total" style="float:right;">
      </el-pagination>
    </el-col>

    <!-- 编辑界面  :visible.sync 控制当前窗体是否显示  :rules  表单校验引用规则  ref=  给当前表单取一个引用别名 -->
    <el-dialog :title="title" :visible.sync="departmentFormVisible" :close-on-click-modal="false">
      <el-form :model="departmentForm" label-width="80px" :rules="departmentFormRules" ref="departmentForm">
        <!--prop="name"  申明表单中有一个属性name-->
        <el-form-item label="名称" prop="name">
          <el-input v-model="departmentForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="编号" prop="sn">
          <el-input v-model="departmentForm.sn" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="departmentForm.state">
            <el-radio class="radio" :label="0">启用</el-radio>
            <el-radio class="radio" :label="-1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="管理员">
          <!--<el-input v-model="departmentForm.manager" auto-complete="off"></el-input>-->
          <el-select v-model="departmentForm.manager" clearable value-key="id" placeholder="请选择">
            <!--
               clearable  可清空
               <el-option  : 选择项
               :label 选择后展示在选择框中的内容
               :value 选择后你要传送给后端的值
            -->
            <el-option
                v-for="item in employees"
                :key="item.id"
                :label="item.username"
                :value="item">
              <span style="float: left">{{ item.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}</span>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="上级部门">
          <!--<el-input v-model="departmentForm.parent" auto-complete="off"></el-input>-->
          <!--:label 选择后展示在选择框中的内容
               :value 选择后你要传送给后端的值-->
          <el-cascader v-model="departmentForm.parent"
               :options="deptTree"
               :props="{
							   checkStrictly: true,
							   label: 'name',
							   value: 'id'
							}"
              clearable>
          </el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="departmentFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="departmentSubmit" :loading="departmentLoading">提交</el-button>
      </div>
    </el-dialog>


  </section>
</template>

  <script>
    import util from '../../common/js/util'
    //import NProgress from 'nprogress'
    import {
      getDepartmentListPage,
      removeDepartment,
      batchRemoveDepartment,
      departmentDepartment,
      addDepartment
    } from '../../api/api';

    export default {
      data() {
        return {
          filters: {
            keywords: ''
          },
          deptTree: [],
          departments: [],
          employees: [],
          currentPage: 1,
          total: 0,
          pageSize: 10,
          title:'',
          listLoading: false,
          sels: [], // 列表选中列
          departmentFormVisible: false,// 编辑界面是否显示
          departmentLoading: false,
          departmentFormRules: {// 申明表单中属性的校验规则
            name: [
              {required: true, message: '请输入姓名吧', trigger: 'blur'}
            ],
            sn: [
              {required: true, message: '请输入编号吧', trigger: 'blur'}
            ]
          },
          // 编辑界面数据
          departmentForm: {
            id: null,
            name: "",
            sn: "",
            state: 0,
            manager: null,
            parent: null
          },

        }
      },

      /* methods 方法头部*/
      methods: {
        search(){
          this.currentPage = 1;
          this.getDepartments();
        },
        handleCurrentChange(currentPage) {
          this.currentPage = currentPage;
          this.getDepartments();
        },
        // 获取部门列表
        getDepartments() {
          let para = {
            currentPage: this.currentPage,
            keywords: this.filters.keywords,
            pageSize:this.pageSize
          };
          this.listLoading = true;// 开启忙等框
          this.$http.post("/dept", para)// 请求地址：后台的dept接口
              .then(result => {
                result = result.data;// 将列表数据PageList{total rows}赋值给result
                this.departments = result.rows;

                this.listLoading = false;// 关闭忙等框
                this.total = result.total;
              })
              .catch(result => {
                console.log(result);
                alert("系统快爆炸了！");
              })
        },
        // 删除
        handleDel: function (index, row) {
          this.$confirm('确认删除该记录吗?', '强制提醒', {// 弹出删除提示框
            type: 'warning'
          }).then(() => {// 如果成功，则执行以下操作
            this.listLoading = true;// 打开忙等框
            let para = {id: row.id};// 获取当前行的id
            this.$http.delete("/dept/" + row.id)// 发起axios请求
                .then(result => {// 如果成功，则提示用户
                  this.listLoading = false;// 关闭忙等框
                  if (result.data.success) {
                    this.$message({
                      message: "删除成功",
                      type: "success"
                    })
                  } else {
                    this.$message({
                      message: "删除失败",
                      type: "error"
                    })
                  }
                  this.currentPage = 1;// 删除成功后再定位到第一页
                  this.getDepartments();// 重新刷新列表

                }).catch(result => {// 不成功则发送错误信息提醒用户
              this.listLoading = false;// 关闭忙等框
              this.$message({
                message: "删除失败",
                type: "error"
              })
            })

          }).catch(() => {// 如果用户点击取消，则不执行任何操作

          });
        },
        // 显示编辑界面
        handleEdit: function (index, row) {
          this.getDeptTree();
          this.title = "修改";
          this.departmentFormVisible = true;
          this.departmentForm = Object.assign({}, row);// 克隆一份当前列数据做回显
          let dirPath = row.dirPath;// 获取当前列的层级目录
          if (dirPath) {// 判断，如果dirPath不等于空的话
            let array = dirPath.split("/");// 就通过/分割
            let parent = [];// 申明一个空数组赋值给父节点
            for (let i = 1; i < array.length - 1; i++) {// 从下标1开始遍历分割后获得的数组，
              parent.push(parseInt(array[i]));// 将遍历后的值转换为整数后添加到父节点
            }
            this.departmentForm.parent = parent;
          }
        },

        // 显示新增界面
        handleAdd: function () {
          this.getDeptTree();
          this.departmentFormVisible = true;
          this.title = "添加",
              this.departmentForm = {// 显示表单时先清空表单
                id: null,
                name: "",
                sn: "",
                state: 0,
                manager: null,
                parent: null
              };
        },
        // 提交表单
        departmentSubmit: function () {
          // validate开启表单校验
          this.$refs.departmentForm.validate((valid) => {
            if (valid) {// 如果校验通过，执行下面操作
              this.$confirm('确认提交吗？', '强制提示', {}).then(() => {
                this.departmentLoading = true;// 开启忙等框
                let para = Object.assign({}, this.departmentForm);// 复制表单数据
                if (para.parent) {
                  let parent = para.parent;
                  let pid = parent[parent.length - 1];
                  para.parent = {"id": pid};
                }
                this.$http.put("/dept", para)
                    .then(result => {
                      result = result.data;
                      this.departmentLoading = false;// 关闭忙等框
                      this.departmentFormVisible = false;// 关闭模态框
                      if (result.success) {
                        this.$message({
                          message: "操作成功！",
                          type: "success"
                        });
                      } else {
                        this.$message({
                          message: "操作失败！！",
                          type: "error"
                        });
                      }

                      this.page = 1;// 跳转到第一页
                      this.getDepartments();// 重新刷新页面
                    })
                    .catch(result => {
                      this.departmentLoading = false;
                      this.$message({
                        message: "操作失败",
                        type: "error"
                      })
                    })


              });
            }
          });


        },


        selsChange: function (sels) {// 封装被选中的对象
          this.sels = sels;
          console.log(this.sels)
        },
        // 批量删除，
        batchRemove: function () {
          var ids = this.sels.map(item => item.id);
          this.$confirm('确认删除选中记录吗？', '强制提示', {
            type: 'warning'
          }).then(() => {
            this.listLoading = true;// 打开忙等框
            this.$http.patch("/dept/", ids)
                .then(result => {// 如果成功，就走这里
                  result = result.data;
                  if (result.success) {
                    this.$message({
                      message: '删除成功',
                      type: 'success'
                    });
                  } else {
                    this.$message({
                      message: '删除失败',
                      type: 'error'
                    });
                  }
                  this.currentPage = 1;// 删除成功后再定位到第一页
                  this.getDepartments();// 重新刷新列表
                })
                .catch(result => {
                  alert("系统错误")
                })
                .catch(result => {// 不成功，就没动作
                })
          }).catch(() => {
          });
        },
        // 获取员工列表数据
        getEmployees(){
          this.$http.get("/employee")
              .then(result => {
                result = result.data;
                this.employees = result
              })
              .catch(result => {
              })
        },

       getDeptTree(){// 获取部门级联树
          this.$http.get("/dept/tree")
            .then(result => {
              result = result.data;
              this.deptTree = result;
            })
        }




      },
      /* methods 方法尾部*/

      mounted() {
        this.getDepartments();// 页面加载完毕后立即加载部门和员工列表
        this.getEmployees();
      }
    }

  </script>

  <style scoped>

  </style>
